package com.lagou.edu.authority.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lagou.edu.authority.dto.RoleDTO;
import com.lagou.edu.authority.entity.Role;
import com.lagou.edu.authority.param.RoleQueryParam;
import com.lagou.edu.authority.service.IRoleService;
import com.lagou.edu.common.util.ConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色接口
 *
 * @author lm
 * @since 2021/11/4 14:22
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    IRoleService roleService;

    @PostMapping("/saveOrUpdate")
    public boolean saveOrUpdateRole(@RequestBody RoleDTO roleDTO) {
        Role role = ConvertUtils.convert(roleDTO, Role.class);
        role.setUpdatedTime(new Date());
        return roleService.saveOrUpdate(role);
    }

    @PostMapping("/getRolePages")
    public Page<RoleDTO> getRolePages(@RequestBody RoleQueryParam roleQueryParam) {
        Page<Role> rolePages = roleService.getRolePages(roleQueryParam);
        Page<RoleDTO> roleDTOPages = new Page<>();
        BeanUtils.copyProperties(rolePages, roleDTOPages);
        if (CollectionUtils.isNotEmpty(rolePages.getRecords())) {
            List<RoleDTO> records = rolePages.getRecords().stream()
                    .map(role -> ConvertUtils.convert(role, RoleDTO.class)).collect(Collectors.toList());
            roleDTOPages.setRecords(records);
        }
        return roleDTOPages;
    }

    @GetMapping({"id"})
    public Boolean deleteRoleByRoleId(@PathVariable("id") Integer id) {
        return roleService.deleteRoleByRoleId(id);
    }
}
